package top.caulife.lab.service;


import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import top.caulife.lab.entity.ProPartialInfo;
import top.caulife.lab.entity.SimpleProInfo;
import top.caulife.lab.mapper.ProPartialInfoMapper;
import top.caulife.lab.mapper.SimpleProInfoMapper;

import java.util.*;

@Service
public class SimpleProInfoService {
    @Autowired
    SimpleProInfoMapper simpleProInfoMapper;

    public List<ProjectInfo> sel(String pi_id){
        List<SimpleProInfo> simpleProInfos= simpleProInfoMapper.sel(pi_id);

        List<ProjectInfo> projectInfos = new ArrayList<>();

        for (SimpleProInfo proInfo:simpleProInfos) {
            insertInfo(projectInfos,proInfo);
        }

        return projectInfos;
    }

    @Data
    @AllArgsConstructor
    static class ExpInfo{
        String exp_id;
        String exp_name;
        List<SimpleProInfo> children;
    }

    @Data
    @AllArgsConstructor
    public static class ProjectInfo{
        String project_id;
        String project_name;
        List<ExpInfo> children;
    }

    static void insertInfo(List<ProjectInfo> projectInfos,SimpleProInfo proInfo){
        for (ProjectInfo projectInfo:projectInfos) {
            if (projectInfo.project_id.equals(proInfo.getProject_id())){
                for (ExpInfo expInfo:projectInfo.children) {
                    if (expInfo.exp_id.equals(proInfo.getExp_id())){
                        expInfo.children.add(proInfo);
                        return;
                    }
                }
                List<SimpleProInfo> lis_proInfo = new ArrayList<>();
                lis_proInfo.add(proInfo);
                projectInfo.children.add(
                        new ExpInfo(
                                proInfo.getExp_id(),
                                proInfo.getExp_name(),
                                lis_proInfo));
                return;
            }
        }

        List<SimpleProInfo> lis_proInfo = new ArrayList<>();
        lis_proInfo.add(proInfo);
        List<ExpInfo> lis_expInfo = new ArrayList<>();
        lis_expInfo.add(
                new ExpInfo(
                        proInfo.getExp_id(),
                        proInfo.getExp_name(),
                        lis_proInfo));

        projectInfos.add(
                new ProjectInfo(
                        proInfo.getProject_id(),
                        proInfo.getProject_name(),
                        lis_expInfo));
    }


    void insertNewRecord(SimpleProInfo simpleProInfo){
        simpleProInfoMapper.insertNew(simpleProInfo);
    }
}
